<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      class="u-mb20"
    >
      <el-breadcrumb-item>
        <span
          class="c-text-high u-cursor"
          @click="back"
        >广告单元</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}广告单元</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 创建广告单元 -->
    <SectionContainer class="u-p30 u-mb30">
      <el-form
        ref="cellForm"
        :model="cellData"
        :rules="cellRules"
        label-width="160px"
      >
        <!--投放信息-->
        <SectionTitle class="u-mb30">投放信息</SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="planId"
            label="广告计划"
          >
            <el-select
              :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
              v-model="cellData.planId"
              placeholder="请选择广告计划"
              filterable
              class="u-w450"
            >
              <el-option
                v-for="item in planOptions"
                :key="item.planId"
                :label="item.planName"
                :value="item.planId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="unitName"
            label="单元名称"
          >
            <el-input
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.unitName"
              placeholder="不可重复、不可包含特殊字符"
              class="u-w450"
            >
            </el-input>
            <ShowWordLimit
              :value="cellData.unitName"
              :maxlength="50"
            ></ShowWordLimit>
          </el-form-item>
        </div>

        <!--媒体信息-->
        <SectionTitle class="u-pt30 u-mb30">媒体信息</SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="platform"
            label="推广类型"
          >
            <el-radio-group v-model="cellData.platform">
              <el-radio
                :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
                v-for="item in GENERALIZE_CELL_PLATFORM"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="mediaValue"
            label="投放媒体"
          >
            <el-radio-group v-model="cellData.mediaChoice">
              <el-radio
                :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.mediaChoice === 1">
              <DropMedia
                @change="dropMediaChange"
                @space-price="dropMediaSpacePrice"
                :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
                :media="cellData.media"
                :media-value="cellData.mediaValue"
                :media-echo="cellData.mediaEcho"
              ></DropMedia>
            </CustomContainer>
          </el-form-item>
        </div>

        <!--定向投放-->
        <SectionTitle class="u-pt30 u-mb30">定向投放</SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="area"
            label="投放地域"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.areaChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.areaChoice === 1">
              <DropArea
                :disabled="['detail'].indexOf(pageAction) !== -1"
                :area-code.sync="cellData.areaCode"
                :area.sync="cellData.area"
                :area-quick.sync="cellData.areaQuick"
              ></DropArea>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="age"
            label="年龄群体"
            v-show="cellData.platform === 0"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.ageChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.ageChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.age"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_AGE"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            label="性别"
            v-show="cellData.platform === 0"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.selectGender"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_GENDER"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="networkingType"
            label="网络环境"
            v-show="cellData.platform === 0"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.networkingTypeChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.networkingTypeChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.networkingType"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_NETWORK"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="mobileOperator"
            label="移动运营商"
            v-show="cellData.platform === 0"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.mobileOperatorChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.mobileOperatorChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.mobileOperator"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_OPERATOR"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            label="终端设备"
            v-show="cellData.platform === 0"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.selectTerminal"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_TERMINAL"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="phoneBrand"
            label="手机品牌"
            v-show="cellData.platform === 0 && cellData.selectTerminal !== 1"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.phoneBrandChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.phoneBrandChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.phoneBrand"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_PHONE_BRAND"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="systemMobile"
            label="系统版本号"
            v-show="cellData.platform === 0 && cellData.selectTerminal !== 1"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.systemMobileChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.systemMobileChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.systemMobile"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_PHONE_VERSION"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="systemVersion"
            label="操作系统"
            v-show="cellData.platform === 1"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.systemVersionChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.systemVersionChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.systemVersion"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_SYSTEM"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="browser"
            label="浏览器"
            v-show="cellData.platform === 1"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.browserChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.browserChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.browser"
              >
                <el-checkbox
                  v-for="item in GENERALIZE_CELL_BROWSER"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="interest"
            label="兴趣分类"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.interestChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.interestChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.interest"
              >
                <el-checkbox
                  v-for="item in INTEREST_CLASSIFY"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="phoneGrade"
            label="手机档次"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.phoneGradeChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer v-show="cellData.phoneGradeChoice === 1">
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.phoneGrade"
              >
                <el-checkbox
                  v-for="item in PHONE_LEVEL"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="appDirectional"
            label="定向APP"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.appDirectionalChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer
              style="max-height: 400px; overflow: auto;"
              v-show="cellData.appDirectionalChoice === 1"
            >
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.appDirectional"
              >
                <el-checkbox
                  v-for="item in APP_DIRECT"
                  :label="item.label"
                  :key="item.value"
                ></el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            prop="appFilter"
            label="排除APP"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.appFilterChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer
              style="max-height: 400px; overflow: auto;"
              v-show="cellData.appFilterChoice === 1"
            >
              <el-checkbox-group
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.appFilter"
              >
                <el-checkbox
                  v-for="item in APP_DIRECT"
                  :label="item.label"
                  :key="item.id"
                ></el-checkbox>
              </el-checkbox-group>
            </CustomContainer>
          </el-form-item>
          <el-form-item
            label="目标人群"
            prop="crowd"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.crowdChoice"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_LIMIT"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
            <CustomContainer
              style="max-height: 400px; overflow: auto;"
              v-show="cellData.crowdChoice === 1"
            >
              <Orientation
                :data="crowdOptions"
                :checked.sync="cellData.crowd"
                :disabled="['detail'].indexOf(pageAction) !== -1"
                @change="$refs.cellForm.validateField('crowd')"
              ></Orientation>
            </CustomContainer>
          </el-form-item>
        </div>

        <!--预算和时间-->
        <SectionTitle class="u-pt30 u-mb30">预算和时间</SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="budget"
            label="每日预算"
            class="u-mb15"
          >
            <el-row type="flex">
              <el-input
                :disabled="['detail'].indexOf(pageAction) !== -1 || cellData.whetherBudget === 1"
                class="u-mr20 u-w200"
                v-model="cellData.budget"
                placeholder="最低0.1"
              >
                <template slot="append">元</template>
              </el-input>
              <el-checkbox
                :disabled="['detail'].indexOf(pageAction) !== -1"
                v-model="cellData.whetherBudget"
                :true-label="1"
                :false-label="0"
                @change="cellData.budget = ''"
              >不限预算</el-checkbox>
            </el-row>
          </el-form-item>
          <el-form-item>
            <Tip class="u-lh24">
              注：<br>
              1、当日消费达到每日预算设定的金额之后会停止展现广告，由于系统延迟，可能会有少量的超预算展现<br>
              2、每日预算金额需大于今日已消耗金额
            </Tip>
          </el-form-item>
          <el-form-item
            prop="cycleDaterange"
            label="投放周期"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.cycleChoice"
            >
              <el-radio :label="0">从今天开始长期投放</el-radio>
              <el-radio :label="1">设置开始和结束日期</el-radio>
            </el-radio-group>
            <el-row
              class="u-mt10"
              v-show="cellData.cycleChoice === 1"
            >
              <el-date-picker
                :disabled="['detail'].indexOf(pageAction) !== -1"
                :clearable="false"
                v-model="cellData.cycleDaterange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="DATERANGE_DISABLED_BEFORE"
              >
              </el-date-picker>
            </el-row>
          </el-form-item>
          <el-form-item
            prop="scheduleWeek"
            label="投放时段"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.scheduleChoice"
            >
              <el-radio :label="0">不限时段</el-radio>
              <el-radio :label="1">自定义</el-radio>
            </el-radio-group>
            <DropTime
              v-show="cellData.scheduleChoice === 1"
              :disabled="['detail'].indexOf(pageAction) !== -1"
              :value.sync="cellData.scheduleWeek"
              @change="scheduleWeekChange"
              class="u-mt10"
            ></DropTime>
          </el-form-item>
          <el-form-item prop="budgetCtrl">
            <span slot="label">投放方式
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
              >
                <div
                  class="u-w200"
                  slot="content"
                >
                  标准投放：系统会自动优化您的投放，让预算在设定的时间段内稳定的消耗完，以尽可能地从流量中挑选最匹配的流量。<br>
                  加速投放：尽可能的将广告投放出去，可能会在较短的时间内消耗完预算，也可能会因为竞争环境的变化导致预算消耗出现较大的波动。<br>
                  在投放周期内，如果预算消耗小于预期，建议通过优化创意、调整受众人群和出价的方式进行优化，和投放方式选择无关。</div>
                <i class="iconfont iconfont-10 c-hint-major"></i>
              </el-tooltip>
            </span>
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.budgetCtrl"
            >
              <el-radio :label="0">标准投放</el-radio>
              <el-radio :label="1">加速投放</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!--出价-->
        <SectionTitle class="u-pt30 u-mb30">出价</SectionTitle>
        <div>
          <el-form-item
            prop="costType"
            label="付费方式"
          >
            <el-radio-group
              :disabled="['detail'].indexOf(pageAction) !== -1"
              v-model="cellData.costType"
            >
              <el-radio
                v-for="item in GENERALIZE_CELL_COST"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="defaultPrice"
            label="出价"
          >
            <el-input
              :disabled="['detail'].indexOf(pageAction) !== -1"
              placeholder="最低0.1"
              class="u-w200"
              v-model="cellData.defaultPrice"
            >
              <template slot="append">元</template>
            </el-input>
            <Tip
              v-if="cellData.remarks"
              class="u-ml10"
              inline
            >{{suggestPrice(cellData.remarks)}}</Tip>
          </el-form-item>
          <el-form-item v-if="cellData.remarks">
            <Tip class="u-lh24">
              注：<br>
              1、建议高于底价范围出价<br>
              2、如果希望获得更多的量，可适当提高出价增加广告竞争力
            </Tip>
          </el-form-item>
        </div>
      </el-form>
    </SectionContainer>
    <div class="u-affix-bottom u-page-handle">
      <el-button
        size="small"
        @click="back"
      >返回</el-button>
      <el-button
        v-if="['create', 'copy'].indexOf(pageAction) !== -1"
        @click="performAction('create')"
        type="primary"
        size="small"
      >创建广告创意</el-button>
      <el-button
        v-if="['create', 'copy', 'edit'].indexOf(pageAction) !== -1"
        @click="performAction('save')"
        type="primary"
        size="small"
      >保存</el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";

import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import Tip from "@/components/tip";
import ShowWordLimit from "@/components/show-word-limit";
import CustomContainer from "@/components/custom-container";
import DropArea from "./components/drop-area";
import DropMedia from "./components/drop-media";
import DropTime from "./components/drop-time";
import Orientation from "./components/orientation";

import {
  INTEREST_CLASSIFY,
  PHONE_LEVEL,
  APP_DIRECT
} from "@/assets/js/common-option";
import DATERANGE_OPTIONS, {
  DATERANGE_DISABLED_BEFORE
} from "@/assets/js/daterange-option";
import { getStrLen, sessionStorage, suggestPrice } from "@/utils";
import {
  GENERALIZE_CELL_LIMIT,
  GENERALIZE_CELL_PLATFORM,
  GENERALIZE_CELL_AGE,
  GENERALIZE_CELL_GENDER,
  GENERALIZE_CELL_NETWORK,
  GENERALIZE_CELL_OPERATOR,
  GENERALIZE_CELL_TERMINAL,
  GENERALIZE_CELL_PHONE_BRAND,
  GENERALIZE_CELL_PHONE_VERSION,
  GENERALIZE_CELL_SYSTEM,
  GENERALIZE_CELL_BROWSER,
  GENERALIZE_CELL_COST
} from "@/assets/js/common-option";
import {
  fetchPlanSelect,
  fetchUnitAdd,
  fetchUnitUpdate,
  fetchUnitDetail,
  fetchCrowdList
} from "@/api";

export default {
  components: {
    SectionContainer,
    SectionTitle,
    DropArea,
    DropTime,
    Tip,
    CustomContainer,
    DropMedia,
    ShowWordLimit,
    Orientation
  },
  data() {
    return {
      INTEREST_CLASSIFY,
      PHONE_LEVEL,
      APP_DIRECT,
      DATERANGE_OPTIONS,
      DATERANGE_DISABLED_BEFORE,
      GENERALIZE_CELL_LIMIT,
      GENERALIZE_CELL_PLATFORM,
      GENERALIZE_CELL_AGE,
      GENERALIZE_CELL_GENDER,
      GENERALIZE_CELL_NETWORK,
      GENERALIZE_CELL_OPERATOR,
      GENERALIZE_CELL_TERMINAL,
      GENERALIZE_CELL_PHONE_BRAND,
      GENERALIZE_CELL_PHONE_VERSION,
      GENERALIZE_CELL_SYSTEM,
      GENERALIZE_CELL_BROWSER,
      GENERALIZE_CELL_COST,

      user: sessionStorage.get("USER"),

      planOptions: [],
      crowdOptions: [],

      pageAction: this.$route.query.action,

      // 单元数据
      cellData: {
        planId: "", // 计划ID
        unitName: "", // 单元名称
        profitPercentage: sessionStorage.get("USER").profitPercentage, // 盈利比
        displayPercentage: sessionStorage.get("USER").displayPercentage, // 曝光数比
        platform: 0, // 推广类型
        mediaChoice: 0, // 投放媒体
        media: 3, // 投放媒体类型
        mediaEcho: "0,0,0,0", // 投放媒体选择内容
        mediaValue: "", // 自定义媒体
        areaChoice: 0, // 投放地域
        area: "", // 自定义投放地域name
        areaCode: "", // 自定义投放地域Key
        areaQuick: "", // 投放地域快捷选择
        ageChoice: 0, // 年龄群体
        age: [], // 年龄群体自定义
        selectGender: 0, // 性别
        networkingTypeChoice: 0, // 网络环境
        networkingType: [], // 网络环境自定义
        mobileOperatorChoice: 0, // 移动运营商
        mobileOperator: [], // 移动运营商自定义
        selectTerminal: 0, // 终端设备
        phoneBrandChoice: 0, // 手机品牌
        phoneBrand: [], // 手机品牌自定义
        systemMobileChoice: 0, // 系统版本号
        systemMobile: [], // 系统版本号自定义
        systemVersionChoice: 0, // 操作系统
        systemVersion: [], // 操作系统自定义
        browserChoice: 0, // 浏览器
        browser: [], // 浏览器自定义
        interestChoice: 0, // 兴趣分类
        interest: [], // 兴趣分类自定义
        phoneGradeChoice: 0, // 手机档次
        phoneGrade: [],
        appDirectionalChoice: 0, // APP定向
        appDirectional: [],
        appFilterChoice: 0, // APP排除
        appFilter: [],
        crowdChoice: 0, // 目标人群
        crowd: "",
        budget: "", // 每日预算
        whetherBudget: 1, // 不设预算
        cycleChoice: 0, // 投放周期
        cycleDaterange: [], // 投放周期时间段
        startTime: "", // 自定义投放周期
        endTime: "", // 自定义投放周期
        scheduleChoice: 0, // 投放时段
        scheduleWeek: "", // 投放时段自定义
        budgetCtrl: 0, // 投放方式
        costType: 0, // 付费方式
        defaultPrice: "", // 出价
        remarks: "" // 底价范围："最小~最大"
      },
      cellRules: {
        planId: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择广告计划"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        unitName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入单元名称"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("单元名称不能超过50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        platform: {
          required: true,
          message: "请选择推广类型",
          trigger: ["change", "blur"]
        },
        mediaValue: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.cellData.mediaChoice === 1 && value === "") {
              callback(new Error("请选择投放媒体"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        area: {
          validator: (rule, value, callback) => {
            if (this.cellData.areaChoice === 1 && value === "") {
              callback(new Error("请选择投放地域"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        age: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 0) {
              if (this.cellData.ageChoice === 1 && !value.length) {
                callback(new Error("请选择年龄群体"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        networkingType: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 0) {
              if (this.cellData.networkingTypeChoice === 1 && !value.length) {
                callback(new Error("请选择网络环境"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        mobileOperator: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 0) {
              if (this.cellData.mobileOperatorChoice === 1 && !value.length) {
                callback(new Error("请选择移动运营商"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        phoneBrand: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 0) {
              if (this.cellData.phoneBrandChoice === 1 && !value.length) {
                callback(new Error("请选择手机品牌"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        systemMobile: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 0) {
              if (this.cellData.systemMobileChoice === 1 && !value.length) {
                callback(new Error("请选择系统版本号"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        systemVersion: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 1) {
              if (this.cellData.systemVersionChoice === 1 && !value.length) {
                callback(new Error("请选择操作系统"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        browser: {
          validator: (rule, value, callback) => {
            if (this.cellData.platform === 1) {
              if (this.cellData.browserChoice === 1 && !value.length) {
                callback(new Error("请选择浏览器"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        interest: {
          validator: (rule, value, callback) => {
            if (this.cellData.interestChoice === 1 && !value.length) {
              callback(new Error("请选择兴趣分类"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        phoneGrade: {
          validator: (rule, value, callback) => {
            if (this.cellData.phoneGradeChoice === 1 && !value.length) {
              callback(new Error("请选择手机档次"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        appDirectional: {
          validator: (rule, value, callback) => {
            if (this.cellData.appDirectionalChoice === 1 && !value.length) {
              callback(new Error("请选择定向APP"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        appFilter: {
          validator: (rule, value, callback) => {
            if (this.cellData.appFilterChoice === 1 && !value.length) {
              callback(new Error("请选择排除APP"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        crowd: {
          validator: (rule, value, callback) => {
            if (this.cellData.crowdChoice === 1 && !value) {
              callback(new Error("请选择目标人群"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        budget: {
          required: true,
          validator: (rule, value, callback) => {
            // 限制预算才验证预算
            if (this.cellData.whetherBudget === 0) {
              if (!value || String(value).trim() === "") {
                callback(new Error("请输入每日预算"));
              } else if (value < 0.01 || isNaN(value)) {
                callback(new Error("每日预算最低0.01"));
              } else if (
                String(value).length > String(Number(value).toFixed(2)).length
              ) {
                callback(new Error("每日预算请保留2位小数"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        cycleDaterange: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.cellData.cycleChoice === 1 && !value.length) {
              callback(new Error("请选择投放周期"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        scheduleWeek: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.cellData.scheduleChoice === 1 && value === "") {
              callback(new Error("请选择投放时段"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        budgetCtrl: {
          required: true,
          message: "请选择投放方式",
          trigger: ["change", "blur"]
        },
        costType: {
          required: true,
          message: "请选择付费方式",
          trigger: ["change", "blur"]
        },
        defaultPrice: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || String(value).trim() === "") {
              callback(new Error("请输入出价"));
            } else if (value < 0.1 || isNaN(value)) {
              callback(new Error("出价最低0.1"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("出价请保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "创建",
        edit: "编辑",
        copy: "复制",
        detail: "查看"
      }[this.pageAction];
    },
    submitCellData() {
      let {
        id,
        planId,
        unitName,
        profitPercentage,
        displayPercentage,
        platform,
        mediaChoice,
        media,
        mediaEcho,
        areaChoice,
        ageChoice,
        selectGender,
        networkingTypeChoice,
        mobileOperatorChoice,
        selectTerminal,
        phoneBrandChoice,
        systemMobileChoice,
        systemVersionChoice,
        browserChoice,
        budget,
        whetherBudget,
        cycleChoice,
        scheduleChoice,
        budgetCtrl,
        costType,
        defaultPrice,
        area,
        areaCode,
        areaQuick,
        mediaValue,
        age,
        networkingType,
        mobileOperator,
        phoneBrand,
        systemMobile,
        systemVersion,
        browser,
        scheduleWeek,
        cycleDaterange,
        remarks,
        appFilterChoice,
        appDirectionalChoice,
        phoneGradeChoice,
        interestChoice,
        appFilter,
        appDirectional,
        phoneGrade,
        interest,
        crowdChoice,
        crowd
      } = this.cellData;
      let ret = {
        planId,
        unitName,
        profitPercentage,
        displayPercentage,
        platform,
        mediaChoice,
        media,
        mediaEcho,
        mediaValue,
        areaChoice,
        ageChoice,
        selectGender,
        networkingTypeChoice,
        mobileOperatorChoice,
        selectTerminal,
        phoneBrandChoice,
        systemMobileChoice,
        systemVersionChoice,
        browserChoice,
        whetherBudget,
        cycleChoice,
        scheduleChoice,
        budgetCtrl,
        costType,
        defaultPrice,
        area,
        areaCode,
        scheduleWeek,
        remarks,
        areaQuick,
        budget: budget || 0,
        startTime: cycleDaterange[0] || "",
        endTime: cycleDaterange[1] || "",
        age: age.join(),
        networkingType: networkingType.join(),
        mobileOperator: mobileOperator.join(),
        phoneBrand: phoneBrand.join(),
        systemMobile: systemMobile.join(),
        systemVersion: systemVersion.join(),
        browser: browser.join(),
        appFilterChoice,
        appDirectionalChoice,
        phoneGradeChoice,
        interestChoice,
        appFilter: appFilter.join(),
        appDirectional: appDirectional.join(),
        phoneGrade: phoneGrade.join(),
        interest: interest.join(),
        crowdChoice,
        crowd
      };
      // 编辑多一个id
      if (this.pageAction === "edit") {
        Object.assign(ret, {
          id
        });
      }
      return ret;
    }
  },
  methods: {
    suggestPrice,

    // 返回
    back() {
      this.$router.replace({
        name: this.$route.query.referrer,
        query: {
          ...this.$route.query.query
        }
      });
    },
    // 获取人群包
    fetchCrowdList() {
      return fetchCrowdList({
        query: {
          userId: this.user.userId
        }
      }).then(res => {
        this.crowdOptions = res.data.list;
      });
    },
    // 广告计划下拉数据
    fetchPlanSelect() {
      return fetchPlanSelect({
        query: {
          userId: this.user.userId
        }
      }).then(res => {
        this.planOptions = res.data;
        if (this.$route.query.planId) {
          this.cellData.planId = Number(this.$route.query.planId);
        }
      });
    },
    // 详情
    fetchUnitDetail() {
      fetchUnitDetail({
        query: {
          id: this.$route.query.unitId
        }
      }).then(res => {
        let {
          id,
          planId,
          unitName,
          profitPercentage,
          displayPercentage,
          platform,
          mediaChoice,
          media,
          mediaEcho,
          mediaValue,
          areaChoice,
          ageChoice,
          selectGender,
          networkingTypeChoice,
          mobileOperatorChoice,
          selectTerminal,
          phoneBrandChoice,
          systemMobileChoice,
          systemVersionChoice,
          browserChoice,
          budget,
          whetherBudget,
          cycleChoice,
          scheduleChoice,
          budgetCtrl,
          costType,
          defaultPrice,
          area,
          areaCode,
          areaQuick,
          startTime,
          endTime,
          age,
          networkingType,
          mobileOperator,
          phoneBrand,
          systemMobile,
          systemVersion,
          browser,
          scheduleWeek,
          remarks,
          appFilterChoice,
          appDirectionalChoice,
          phoneGradeChoice,
          interestChoice,
          appFilter,
          appDirectional,
          phoneGrade,
          interest,
          crowdChoice,
          crowd
        } = res.data;
        // 编辑/复制默认
        Object.assign(this.cellData, {
          id,
          planId,
          unitName,
          profitPercentage,
          displayPercentage,
          platform,
          mediaChoice,
          media,
          mediaEcho,
          mediaValue,
          areaChoice,
          ageChoice,
          selectGender,
          networkingTypeChoice,
          mobileOperatorChoice,
          selectTerminal,
          phoneBrandChoice,
          systemMobileChoice,
          systemVersionChoice,
          browserChoice,
          whetherBudget,
          cycleChoice,
          scheduleChoice,
          budgetCtrl,
          costType,
          defaultPrice,
          area,
          areaCode,
          scheduleWeek,
          remarks,
          areaQuick,
          budget: budget || "",
          appFilterChoice,
          appDirectionalChoice,
          phoneGradeChoice,
          interestChoice,
          cycleDaterange: [startTime, endTime],
          age: this.initCellDataCheckbox(ageChoice, age),
          networkingType: this.initCellDataCheckbox(
            networkingTypeChoice,
            networkingType
          ),
          mobileOperator: this.initCellDataCheckbox(
            mobileOperatorChoice,
            mobileOperator
          ),
          phoneBrand: this.initCellDataCheckbox(phoneBrandChoice, phoneBrand),
          systemMobile: this.initCellDataCheckbox(
            systemMobileChoice,
            systemMobile
          ),
          systemVersion: this.initCellDataCheckbox(
            systemVersionChoice,
            systemVersion
          ),
          browser: this.initCellDataCheckbox(browserChoice, browser),
          appFilter: this.initCellDataCheckbox(appFilterChoice, appFilter),
          appDirectional: this.initCellDataCheckbox(
            appDirectionalChoice,
            appDirectional
          ),
          phoneGrade: this.initCellDataCheckbox(phoneGradeChoice, phoneGrade),
          interest: this.initCellDataCheckbox(interestChoice, interest),
          crowdChoice,
          crowd
        });
      });
    },
    // 初始化定向相关checkbox多项选择
    initCellDataCheckbox(type, value) {
      if (type === 0 || !value) return [];
      return value.split(",");
    },
    // 新建、编辑、复制
    initDetail() {
      // 除新建外需要请求已有数据
      if (this.pageAction !== "create") {
        this.fetchUnitDetail();
      }
    },
    // 新建
    addItem() {
      return fetchUnitAdd({
        query: {
          userId: this.user.userId
        },
        body: this.submitCellData
      }).then(res => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
        return res;
      });
    },
    addItemSave() {
      this.$refs["cellForm"].validate((valid, params) => {
        if (valid) {
          this.addItem().then(res => {
            setTimeout(() => {
              let { planId } = res.data;
              this.$router.replace({
                name: "generalize-cell",
                query: {
                  planId
                }
              });
            }, 1000);
          });
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    addItemJump() {
      this.$refs["cellForm"].validate((valid, params) => {
        if (valid) {
          this.addItem().then(res => {
            setTimeout(() => {
              let { planId, unitId } = res.data;
              this.$router.replace({
                name: "generalize-creative-detail",
                query: {
                  action: "create",
                  referrer: "generalize-creative",
                  planId,
                  unitId
                }
              });
            }, 1000);
          });
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 更新
    updateItem() {
      return fetchUnitUpdate({
        query: {
          userId: this.user.userId
        },
        body: this.submitCellData
      }).then(res => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
        return res;
      });
    },
    updateItemSave() {
      this.$refs["cellForm"].validate((valid, params) => {
        if (valid) {
          this.updateItem().then(() => {
            setTimeout(() => {
              this.back();
            }, 1000);
          });
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    updateItemJump() {
      this.$refs["cellForm"].validate((valid, params) => {
        if (valid) {
          this.updateItem().then(res => {
            setTimeout(() => {
              let { planId, unitId } = res.data;
              this.$router.replace({
                name: "generalize-creative-detail",
                query: {
                  action: "create",
                  referrer: "generalize-creative",
                  planId,
                  unitId
                }
              });
            }, 1000);
          });
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 新建、保存、复制
    performAction(type) {
      // 新建
      if ("create" === type) {
        this.addItemJump();
      }
      // 保存
      else if ("save" === type) {
        if ("edit" === this.pageAction) {
          this.updateItemSave();
        } else {
          // 新建、复制
          this.addItemSave();
        }
      }
    },
    // 投放媒体选中内容改变
    dropMediaChange(mediaValue, media, mediaEcho) {
      this.cellData.mediaValue = mediaValue;
      this.cellData.media = media;
      this.cellData.mediaEcho = mediaEcho;
      this.$refs.cellForm.validateField("mediaValue");
    },
    // 投放媒体按广告位的出价范围
    dropMediaSpacePrice(value) {
      this.cellData.remarks = value;
    },
    // 投放时段变更
    scheduleWeekChange() {
      this.$refs.cellForm.validateField("scheduleWeek");
    }
  },
  created() {
    axios.all([this.fetchPlanSelect(), this.fetchCrowdList()]).then(
      axios.spread(() => {
        this.initDetail();
      })
    );
  }
};
</script>